package com.example.fund.updatestategy;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;

import com.example.fund.util.DBManager;

public class FuturesIndexStrategy extends AbstractUpdateStrategy {

	//伦敦金//布伦特原油
	private static final String futuresURL = "http://vip.stock.finance.sina.com.cn/q/view/vFutures_History.php?page=#page&breed=#number&start=#start&type=global";
	
	public FuturesIndexStrategy(String number) {
		super(number);
	}

	@Override
	public boolean isNeedUpdate() {
		return super.isNeedUpdate();
	}



	@Override
	public void updateIndex() {
		SQLiteDatabase db = DBManager.getDB();
		
		String maxDate = getFundMaxDate();

		if(maxDate==null || maxDate.trim().length()==0)
		{
			maxDate = "1996-01-01";
		}
		
		//1.从网络下载。然后截取成XML格式
		String dataURL = futuresURL.replace("#start", maxDate).replace("#number", number);
		int totalPage = 1;
		List<String[]> priceList = new LinkedList<String[]>();
		for(int i=1;i<=totalPage;i++)
		{
			String adataURL = dataURL.replace("#page", i+"");
			HttpURLConnection con = null;
			BufferedReader reader = null;
			
			try
			{
				URL url = new URL(adataURL);
				con = (HttpURLConnection) url.openConnection();
				con.setRequestMethod("GET");
				reader = new BufferedReader(new InputStreamReader(con.getInputStream(),"GBK"));
				boolean start = false;
				boolean end = false;
				StringBuffer sb = new StringBuffer();
				String s = null;
				while((s = reader.readLine())!=null)
				{
					if(start && !end)
					{
						sb.append(s.trim());
//						System.out.println(s);
					}
					if(s.contains("historyList"))
					{
						start = true;
					}
					if(start)
					{
						if(s.contains("</table>"))
						{
							end = true;
						}
					}
					Pattern pattern = Pattern.compile("共(.*)页&");
					Matcher matcher = pattern.matcher(s);
					if(matcher.find())
					{
						totalPage = Integer.valueOf(matcher.group(1).trim());
					}
				}
				if(sb.length()==0)
				{
					break;
				}
				
				//2.解析字符串，并计算成累积净值的形式保存

				Document xmlDoc = null;
				try
				{
					InputStream inputStream = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
					SAXReader sax = new SAXReader();
					xmlDoc = sax.read(inputStream);
				}
				catch (DocumentException e)
				{
					e.printStackTrace();
				}
				catch (UnsupportedEncodingException e)
				{
					e.printStackTrace();
				}
				if(xmlDoc==null)
				{
					break;
				}
				
				Element table = xmlDoc.getRootElement();//根节点
				List trs = table.elements("tr");
				for(int j=1;j<trs.size();j++)
				{
					Element tr = (Element)trs.get(j);
					List tds = tr.elements("td");
					if(tds.size()<2)
					{
						continue;
					}
					String date = ((Element)((Element)tds.get(0)).elements("div").get(0)).getTextTrim();
					String price = ((Element)((Element)tds.get(1)).elements("div").get(0)).getTextTrim();
					if(date!=null && date.compareTo(maxDate)>=0
							&& price!=null)
					{
						String[] strs = new String[2];
						strs[0] = date;
						strs[1] = price;
						priceList.add(strs);
					}
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
			finally
			{
				if(reader!=null)
				{
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(con!=null)
				{
					con.disconnect();
				}
			}
		}
		
		String insertSql = "insert into FundNetValue(id,fundNumber,netValue,date) values (null,?,?,?)";
		SQLiteStatement stmt = db.compileStatement(insertSql);
		db.beginTransaction();
		boolean isFind = false;
		try {
			for(int i=priceList.size()-1;i>=0;i--)
			{
				String[] strs = priceList.get(i);
				if(!isFind && strs[0].equals(maxDate))
				{
					isFind = true;
				}
				if(strs[0].compareTo(maxDate)>0)
				{
				    stmt.bindString(1, number);  
				    stmt.bindDouble(2, Double.valueOf(strs[1]));  
				    stmt.bindString(3, strs[0]);  
				    stmt.execute();  
				    stmt.clearBindings();
				}
			}
			db.setTransactionSuccessful(); 
		} catch (Exception e){
			e.printStackTrace();
		} finally
		{
			db.endTransaction();
		}
	}

}
